#include<bits/stdc++.h>
#define int long long
using namespace std;
namespace IO
{
	template<typename T>
	void read(T &_x){_x=0;int _f=1;char ch=getchar();while(!isdigit(ch)) _f=(ch=='-'?-1:_f),ch=getchar();while(isdigit(ch)) _x=_x*10+(ch^48),ch=getchar();_x*=_f;}
	template<typename T,typename... Args>
	void read(T &_x,Args&...others){Read(_x);Read(others...);}
	const int BUF=20000000;char buf[BUF],top,stk[32];int plen;
	#define pc(x) buf[plen++]=x
	#define flush(); fwrite(buf,1,plen,stdout),plen=0;
	template<typename T>inline void print(T x){if(!x){pc(48);return;}if(x<0) x=-x,pc('-');for(;x;x/=10) stk[++top]=48+x%10;while(top) pc(stk[top--]);}
}
using namespace IO;
const int N = 1010;
int t,n,mod,a[N][N],b[N][N],c[N][N],d[N][N];
signed main()
{
	freopen("matrix.in","r",stdin);
	freopen("matrix1.out","w",stdout);
	read(t);
	while(t--)
	{
		read(mod),read(n);
		for(int i = 1;i <= n;i++)
			for(int j = 1;j <= n;j++)
				read(a[i][j]);
		for(int i = 1;i <= n;i++)
			for(int j = 1;j <= n;j++)
				read(b[i][j]);
		for(int i = 1;i <= n;i++)
			for(int j = 1;j <= n;j++)
				read(c[i][j]),d[i][j] = 0;
		for(int i = 1;i <= n;i++)
			for(int j = 1;j <= n;j++)
				for(int k = 1;k <= n;k++) 
					d[i][j] = (d[i][j]+a[i][k]*b[k][j])%mod;
		int op = 0;
		for(int i = 1;i <= n;i++)
			for(int j = 1;j <= n;j++)
				if(c[i][j] != d[i][j])
				{
					op = 1;
					i = j = n+1;
					break;
				}
		if(!op) pc('Y'),pc('e'),pc('s'),pc('\n');
		else pc('N'),pc('o'),pc('\n');
	}
	flush();
	return 0;
}
/*
dis_{i,j}-a_j <= a_i

*/ 


